<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
        @returnBack="$emit('returnModify')"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t("basic_information") }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :label-width="formInfo.labelWidth"
              :rules="formInfo.rules"
            >
              <template v-slot:form-assetName>
                <el-input
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择资产"
                  v-model="formInfo.data.assetName"
                >
                  <template #append>
                    <el-icon @click="addAsset"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-estimateStartTime>
                <el-date-picker
                  v-model="formInfo.data.estimateStartTime"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  placeholder="预计上机时间"
                >
                </el-date-picker>
              </template>
              <template v-slot:form-estimateEndTime>
                <el-date-picker
                  v-model="formInfo.data.estimateEndTime"
                  type="datetime"
                  disabled
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  placeholder="预计下机时间"
                >
                </el-date-picker>
              </template>
              <template v-slot:form-remindTime>
                <el-date-picker
                  v-model="formInfo.data.remindTime"
                  type="datetime"
                  disabled
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  placeholder="提醒时间"
                >
                </el-date-picker>
              </template>
            </page-form>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 添加资产 -->
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :check-box="false"
      :highlightRow="true"
      @callback="callBackAsset"
    />
  </div>
</template>

<script setup name="equipmentUpDownModify">
import PageForm from "@/components/PageForm/index";
import { addUseManagePage, updateUseManagePage, getUseManageById } from "@/api/asset.js";
import moment from "moment";
import utils from '@/common/js/utils'
import { ElMessage } from 'element-plus'
const { proxy } = getCurrentInstance();
const emit = defineEmits();

const props = defineProps(["visible", "id", "title"]);
const selectAssetInfo = ref({
  visible: false,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      // assetSourceAuth: {
      //   asTbName: 'core_asset,core_asset',
      //   columnName: 'use_dept_id,depot_id',
      //   queryType: 'IN',
      //   queryCategory: 'AND',
      //   value: 'assetSourceAuth',
      // },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
    },
    queryParams: {
      assetUserAndManaDeptAuth: true,
    },
  },
})
const formInfo = ref({
  ref: null,
  data: {
    remindBefore: 5,
    estimateStartTime: moment(new Date()).format("YYYY-MM-DD HH:mm"),
  },
  fieldList: [
    {
      label: "资产名称",
      value: "assetName",
      type: "slot",
    },
    {
      label: "资产卡片号",
      value: "assetCode",
      type: "input",
      disabled: true,
    },
    { label: "规格", value: "standard", type: "input", disabled: true, },
    { label: "生产厂家", value: "brandName", type: "input", disabled: true, },
    { label: "使用科室", value: "useDeptName", type: "input", disabled: true, },
    { label: "病人编号", value: "patientCode", type: "input" },
    { label: "病人姓名", value: "patientName", type: "input" },
    { label: "性别", value: "sex", type: "select-model", code: "sex" },
    { label: "年龄", value: "age", type: "number" },
    { label: "预计上机时间", value: "estimateStartTime", type: "slot" },
    //   TimePickerOptions: {
    //     disabledDate(time) {
    //       return time.getTime() < Date.now()
    //     },
    //   },
    // },
    {
      label: "检查/治疗时间(分钟)",
      value: "estimateTreatDuration",
      type: "number",
    },
    // 预计下机时间=预计上机时间+检查/治疗时间
    {
      label: "预计下机时间",
      value: "estimateEndTime",
      type: "slot",
      disabled: true
    },
    {
      label: "下机提前提醒(分钟)",
      value: "remindBefore",
      type: "number",
      min: -1
    },
    // 提醒时间=预计下机时间-提前提醒时间
    {
      label: "提醒时间",
      value: "remindTime",
      type: "slot",
      disabled: true
    },
  ],
  rules: {
    assetName: [
      { required: true, message: "请选择资产", trigger: "blur" },
    ],
    patientCode: [
      { required: true, message: "请输入病人编号", trigger: "blur" },
    ],
    patientName: [
      { required: true, message: "请输入病人姓名", trigger: "blur" },
    ],
    estimateTreatDuration: [
      { required: true, message: "请输入检查/治疗时间", trigger: "blur" },
    ],
    remindBefore: [
      { required: true, message: "请输入下机提前提醒", trigger: "blur" },
    ],
    estimateStartTime: [
      { required: true, message: "请选择上机时间", trigger: "change" },
    ],
  },
  labelWidth: "140px",
});
const fullInfo = ref({
  btnList: [{ label: "保存", event: save, show: true },{ label: "保存并新增", event: saveAndAdd, show: !props.id }],
});

const showDialog = computed({
  get() {
    return props.visible;
  },
  set(newValue) {
    emit("update:visible", newValue); // 更新父组件visible
  },
});

watch(
  () => formInfo.value.data.estimateStartTime,
  () => {
    setEstimateEndTime()
  }
)
watch(
  () => formInfo.value.data.estimateTreatDuration,
  () => {
    setEstimateEndTime()
  }
)

function setEstimateEndTime () {
  let fmartEstimateStartTime = (new Date(formInfo.value.data.estimateStartTime)).getTime()
  formInfo.value.data.estimateEndTime = utils.switchTime(fmartEstimateStartTime + formInfo.value.data.estimateTreatDuration * 60 * 1000, 'YYYY-MM-DD hh:mm')
}
watch(
  () => formInfo.value.data.estimateEndTime,
  () => {
    setRemindTime()
  }
)
watch(
  () => formInfo.value.data.remindBefore,
  () => {
    setRemindTime()
  }
)

function setRemindTime () {
  let fmartEstimateEndTime = (new Date(formInfo.value.data.estimateEndTime)).getTime()
  formInfo.value.data.remindTime = utils.switchTime(fmartEstimateEndTime - formInfo.value.data.remindBefore * 60 * 1000, 'YYYY-MM-DD hh:mm')
}

onMounted(() => {
  if (props.id) {
    getDetails();
  }
});

//选择资产
function addAsset() {
  selectAssetInfo.value.visible = true;
}

function callBackAsset(data) {
  console.log(data)
  if (data && data.id) {
    formInfo.value.data["assetId"] = data.id;
    formInfo.value.data["assetName"] = data.assetName;
    formInfo.value.data["assetCode"] = data.assetCode;
    formInfo.value.data["standard"] = data.standard;
    formInfo.value.data["brandName"] = data.brandName;
    formInfo.value.data["useDeptName"] = data.useDeptNameRate;
    formInfo.value.data["useDeptId"] = data.useDeptId;

    formInfo.value.data["supplierId"] = data.supplierId;
    formInfo.value.data["supplierName"] = data.supplierName;
    formInfo.value.data["depotName"] = data.depotName;
    formInfo.value.data["depotId"] = data.depotId;
    formInfo.value.data["manageDeptName"] = data.manageDeptName;
    formInfo.value.data["manageDeptId"] = data.manageDeptId;
    formInfo.value.data["location"] = data.location;
  } else {
    formInfo.value.data["assetId"] = "";
    formInfo.value.data["assetName"] = "";
    formInfo.value.data["assetCode"] = "";
    formInfo.value.data["standard"] = "";
    formInfo.value.data["brandName"] = "";
    formInfo.value.data["useDeptName"] = "";
    formInfo.value.data["useDeptId"] = "";

    formInfo.value.data["supplierId"] = "";
    formInfo.value.data["supplierName"] = "";
    formInfo.value.data["depotName"] = "";
    formInfo.value.data["depotId"] = "";
    formInfo.value.data["manageDeptName"] = "";
    formInfo.value.data["manageDeptId"] = "";
    formInfo.value.data["location"] = "";
  }
}
function saveAndAdd() {
  save('saveAndAdd')
}
function save(str = 'save') {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      if(formInfo.value.data.estimateTreatDuration <= formInfo.value.data.remindBefore) {
        ElMessage({
          type: 'warning',
          message: '检查/治疗时间应大于下机提醒时间',
        })
        return
      }
      let api = props.id ? updateUseManagePage : addUseManagePage;
      api(formInfo.value.data).then((res) => {
        if (res && res.success) {
          if (str === 'saveAndAdd') {
            //保存并新增
            formInfo.value.data = {
              remindBefore: 5,
              estimateStartTime: moment(new Date()).format("YYYY-MM-DD HH:mm"),
            }
            proxy.$nextTick(() => {
              formInfo.value.ref.clearValidate()
            })
            emit('update:title', '新增设备启停')
          } else {
            //保存
            showDialog.value = false
            emit('returnModify')
          }
        }
      });
    }
  });
}
function getDetails() {
  getUseManageById(props.id).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data;
      formInfo.value.data = data;
      formInfo.value.data.age = data.age == -2 ? '' : data.age
    }
  });
}
</script>

<style scoped lang="scss">
.flex {
  display: flex;
  // flex: 1;
}
.flex-select :deep(.el-input--small .el-input__inner) {
  height: 28px !important;
}
:deep(.patrolPlan-checkbox) {
  padding: 0 5px 5px 5px;
  box-sizing: border-box;
  .el-checkbox-button__inner {
    width: 30px;
    height: 30px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
:deep(.el-checkbox-button__inner) {
  border: 1px solid #dcdfe6 !important;
}
</style>
